<?php
$class      = $class      ?? "dddd";
$start      = $start      ?? "0";
$step       = $step       ?? "20";
$noticeType = $noticeType ?? -1;


try {
//  $connPdo = new PDO("mysql:host=127.0.0.1:3306;dbname=test;charset=utf8", "root", "");
    $connPdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'squidward_top', '789456');
    $connPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


    // update column state
    $statement = "SELECT * FROM test.$class\nORDER BY ddl DESC";
    $result = $connPdo->query($statement);
    while ($row = $result->fetch()) {
        $nowStamp = time();
        $ddlStamp = strtotime($row["ddl"]);
        $stateNew = $row["state"];

        if ($nowStamp - $ddlStamp > 259200) {
            $stateNew = 3; // 不显示 i.e. 超时 3 天以上
        } else if ($ddlStamp <= $nowStamp) {
            $stateNew = 2; // 超时
        } else if ($ddlStamp - $nowStamp > 86400) {
            $stateNew = 1; // 进行中
        } else {
            $stateNew = 0; // 紧急 i.e. 距 ddl 1 天以内
        }

        if ($stateNew != $row["state"]) {
            $statement =
                "UPDATE test.$class SET\n
 state = $stateNew
 WHERE index_ = ${row['index_']}";

            $connPdo->exec($statement);
        } else if ($stateNew == 3) {
            // ddl DESC 排序，如果已经 discarded 且不需更新则后面也不需更新
            // 这个优化其实没啥用，把上面那个判完之后不交互数据库了，算几个时间戳减法也不浪费时间
            // TODO) 真该优化了的话到时候在 SELECT * 的时候整个 LIMIT
            break;
        }
    }

    /*
     * noticeType == -1 时 查全部 ddl+活动 按照 time DESC
     * noticeType == -2 时 查全部 活动     按照紧急程度 DESC（按照数据库存储格式是 ASC）
     * noticeType > 0   时 查对应 ddl/活动 按照紧急程度 DESC（按照数据库存储格式是 ASC）
     */
    $statement = "SELECT * FROM test.$class";
    if ($noticeType == "-1") {
        $statement .= " ORDER BY time DESC";
    } else if ($noticeType == "-2") {
        $statement .= " WHERE noticeType != 0 ORDER BY state, ddl";
    } else {
        $statement .= " WHERE noticeType = \"$noticeType\" ORDER BY state, ddl";
    }
    $statement .= " LIMIT $start, $step"; //分段获取
    $records = $connPdo->query($statement)->fetchAll();
} catch (PDOException $e) {
    die("query.php 刷新失败\n{$e->getMessage()}");
}
